import { Button, DatePicker, Slider, message } from "antd";
import moment from "moment";
import React, { useCallback, useRef, useState } from "react";
import "../style/DateController.css";

const { RangePicker } = DatePicker;
const timeline = {
  display: "flex",
  position: "absolute",
  bottom: "20px",
  left: "50%",
  transform: "translateX(-50%)",
  width: "80%",
  background: "rgba(2, 16, 25, 0.7)",
  padding: "12px",
  borderRadius: "8px",
  zIndex: 100,
};

const TimelineController = ({ playHeatData, ChangeSource }) => {
  // console.log(playHeatData,'playHeatData')
  const [currentTime, setCurrentTime] = useState(0);
  const [dateRange, setDateRange] = useState();
  // 当 isPlaying 状态更新时，同步更新 useRef 的值
  const [isPlaying, setIsPlaying] = useState(false);
  const [dateArray, setDateArray] = useState([]);
  const [dateTip, setdateTip] = useState([]);
  // 使用 useRef 来存储 isPlaying 的值，确保在闭包中能获取到最新状态
  const isPlayingRef = useRef(isPlaying);
  // 使用 useRef 来存储定时器的 ID
  const intervalRef = useRef(null);
  const intervalheatRef = useRef(null);
  // 用于记录当前截取的起始索引
  const currentIndexRef = useRef(0);
  const disabledDate = (current) => {
    // 禁用当前日期之前的日期
    return current && current > moment().startOf("day");
  };
  React.useEffect(() => {
    isPlayingRef.current = isPlaying;

    if (isPlaying) {
        intervalheat();
      intervalRef.current = setInterval(() => {
        playAnimation();
      }, 500);
    } else {
      // 如果停止播放，清除定时器
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        clearInterval(intervalheatRef.current);
      }
    }

    // 组件卸载时清除定时器，避免内存泄漏
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [isPlaying]);
  // 切换播放/暂停状态
  const togglePlay = () => {
    if (dateArray.length < 1) {
      message.warning("请选择日期");
      return;
    }
    setIsPlaying((prevIsPlaying) => {
      const newIsPlaying = !prevIsPlaying;

      return newIsPlaying;
    });
  };

  // 示例数组，模拟 100 多条数据
  const dataArray = playHeatData;

  let currentIndex = 0;

  // 设置循环定时器
    const intervalheat = () => {
      intervalheatRef.current = setInterval(() => {
        // 计算本次要取出数据的结束索引
        const endIndex = Math.min(currentIndex + 10000, dataArray.length);
        // 取出当前的 10 条数据（或者最后不足 10 条的数据）
        const chunk = dataArray.slice(currentIndex, endIndex);
        
        ChangeSource(chunk);
        // 更新索引
        currentIndex = endIndex;

        // 判断是否已经取完所有数据
        if (currentIndex >= dataArray.length) {
          // 取完数据，停止定时器
          clearInterval(intervalheatRef.current);
          console.log("数据已全部取出，定时器停止。");
        }
      }, 500);
    };

  const COUNT = 5;
  const pushTip = () => {
    const resultArray = dateArray.filter(item =>!dateTip.includes(item));
    const arrayLength = resultArray.length;
    if (arrayLength === 0) {
        const delayTime = (dateTip.length ) * 500 - 1000;
        setTimeout(() => {
            setCurrentTime(0);
            setIsPlaying(false);
            handleDateChange(dateRange);
         
          }, delayTime);
          return null;
    }

    const newArray = resultArray.slice(
      currentIndexRef.current,
      currentIndexRef.current + COUNT
    );
    // 判断是否取到最后一个元素
    if (currentIndexRef.current + newArray.length >= resultArray.length) {
      const delayTime = (newArray.length + 1) * 500;
      setTimeout(() => {
        setIsPlaying(false);
        handleDateChange(dateRange);
        setCurrentTime(0);
      }, delayTime);
    }

    currentIndexRef.current += COUNT;
    if (currentIndexRef.current >= dateArray.length) {
      currentIndexRef.current = 0;
    }
    return newArray;
  };

  const playAnimation = () => {
    // 使用 useRef 存储的 isPlaying 值进行判断
    if (!isPlayingRef.current) return;
    setCurrentTime((prevTime) => {
      let newTime = prevTime + 1;
      if (newTime > dateTip.length) {
        const Tip = pushTip();
        if (Tip) {
          setdateTip(Tip);
        }
        newTime = 0;
      }
      return newTime;
    });
  };

  // 处理日期范围改变事件
  const handleDateChange = (dateStrings) => {
    if (!dateStrings) {
      setdateTip([]);
      return;
    }
    setDateRange(dateStrings);
    const res = getDatesBetween(dateStrings[0], dateStrings[1]);
    const removed = getDatesBetween(dateStrings[0], dateStrings[1]).splice(0, COUNT);
    setdateTip(removed); // 初次展示日期tip
    setDateArray(res);
    currentIndexRef.current = 0;
  };

  const getDatesBetween = useCallback((startDateStr, endDateStr) => {
    const startDate = new Date(startDateStr);
    const endDate = new Date(endDateStr);
    if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
      return [];
    }
    const dates = [];
    let currentDate = new Date(startDate);
    while (currentDate <= endDate) {
      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, "0");
      const day = String(currentDate.getDate()).padStart(2, "0");
      dates.push(`${year}-${month}-${day}`);
      currentDate.setDate(currentDate.getDate() + 1);
    }
    return dates;
  }, []);
  return (
    <div className="timeline-controller" style={timeline}>
      <div
        className="control-buttons"
        style={{ width: "30%", display: "flex" }}
      >
        <RangePicker
          disabledDate={disabledDate}
          allowClear={true}
          onChange={handleDateChange}
          format="YYYY-MM-DD"
          value={dateRange}
        />
        <Button
          type="primary"
          onClick={togglePlay}
          style={{ marginLeft: "5px", marginRight: "5px" }}
        >
          {isPlaying ? "暂停" : "播放"}
        </Button>
      </div>
      <div style={{ width: "70%" }}>
        <div
          style={{
            position: "absolute",
            zIndex: 100,
            display: "flex",
            justifyContent: "space-around",
            width: "70%",
          }}
        >
          {dateTip &&
            dateTip.map((item, index) => {
              return (
                <div key={index} style={{ color: "#fff", marginLeft: "20px" }}>
                  {item}
                </div>
              );
            })}
        </div>

        <Slider
          value={currentTime}
          onChange={(value) => setCurrentTime(value)}
          min={0}
          max={dateTip.length}
          step={1}
        />
      </div>
    </div>
  );
};

export default TimelineController;
